package net.zjitc.android2019.ch3storage;

import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import net.zjitc.android2019.R;

import java.util.HashMap;

public class Ch3QQActivity extends AppCompatActivity {
    EditText ed_name,ed_pwd;
    Button btn_login;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch3_qq);
        init();

        /* 用文件外部存储，先动态申请权限*/
        String[] p={"android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"};
        ActivityCompat.requestPermissions(Ch3QQActivity.this,p,1);

        /* 从sp/文件中获取账号密码并显示在输入框 */
        HashMap<String,String> hashMap=FileSaveQQ.get(Ch3QQActivity.this);
        ed_name.setText(hashMap.get("name"));
        ed_pwd.setText(hashMap.get("pwd"));

        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*1、若输入框为空，则Toast提示不能空
                * 2、若不为空，将账号密码保存：sp  file*/
                String name=ed_name.getText().toString();
                String pwd=ed_pwd.getText().toString();
                if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)){
                    Toast.makeText(Ch3QQActivity.this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
                }else{
                    /*调用SPSaveQQ中的方法完成：将账号密码保存sp*/
                    boolean flag=FileSaveQQ.save(Ch3QQActivity.this,name,pwd);
                    if(flag){
                        Toast.makeText(Ch3QQActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(Ch3QQActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        btn_login.setOnClickListener(listener);

    }




    private void init() {
        ed_name=findViewById(R.id.ch3_qq_ed_number);
        ed_pwd=findViewById(R.id.ch3_qq_ed_password);
        btn_login=findViewById(R.id.ch3_qq_btn_login);
    }
}
